import { Task } from '../database/init'
import { AIContext } from './aiFunctionRegistry'

export interface TaskContextData {
  currentTasks: Task[]
  completedTasks: Task[]
  taskStats: {
    total: number
    pending: number
    inProgress: number
    completed: number
    overdue: number
  }
  recentActivity: TaskActivity[]
  userPreferences: UserPreferences
}

export interface TaskActivity {
  id: string
  taskId: string
  action: 'created' | 'updated' | 'completed' | 'deleted'
  timestamp: Date
  details?: any
}

export interface UserPreferences {
  defaultPriority: 'low' | 'medium' | 'high'
  defaultCategory?: string
  reminderSettings: {
    enabled: boolean
    advanceTime: number // 提前提醒时间（分钟）
  }
  workingHours: {
    start: string // "09:00"
    end: string   // "18:00"
  }
}

class TaskContextProvider {
  // 获取用户任务上下文
  async getTaskContext(userId: string): Promise<TaskContextData> {
    try {
      // 这里应该从数据库获取实际数据
      // 暂时返回模拟数据
      const currentTasks = await this.getCurrentTasks(userId)
      const completedTasks = await this.getCompletedTasks(userId)
      const taskStats = await this.getTaskStats(userId)
      const recentActivity = await this.getRecentActivity(userId)
      const userPreferences = await this.getUserPreferences(userId)

      return {
        currentTasks,
        completedTasks,
        taskStats,
        recentActivity,
        userPreferences
      }
    } catch (error) {
      console.error('Error getting task context:', error)
      throw error
    }
  }

  // 获取当前任务
  private async getCurrentTasks(userId: string): Promise<Task[]> {
    // TODO: 从数据库获取用户当前任务
    // 这里返回模拟数据
    return [
      {
        id: '1',
        title: '完成项目报告',
        description: '编写Q4项目总结报告',
        status: 'in_progress',
        priority: 'P0',
        due_date: '2024-01-15',
        category: 'work',
        tags: ['报告', '项目'],
        completed: false,
        user_id: userId,
        board_position: 0,
        created_at: '2024-01-10T00:00:00Z',
        updated_at: '2024-01-12T00:00:00Z'
      },
      {
        id: '2',
        title: '客户会议',
        description: '与客户讨论新需求',
        status: 'todo',
        priority: 'P1',
        due_date: '2024-01-16',
        category: 'work',
        tags: ['客户', '需求'],
        completed: false,
        user_id: userId,
        board_position: 1,
        created_at: '2024-01-11T00:00:00Z',
        updated_at: '2024-01-11T00:00:00Z'
      }
    ]
  }

  // 获取已完成任务
  private async getCompletedTasks(userId: string): Promise<Task[]> {
    // TODO: 从数据库获取用户已完成任务
    return []
  }

  // 获取任务统计
  private async getTaskStats(userId: string) {
    const currentTasks = await this.getCurrentTasks(userId)
    const now = new Date()
    
    return {
      total: currentTasks.length,
      pending: currentTasks.filter(t => t.status === 'todo').length,
      inProgress: currentTasks.filter(t => t.status === 'in_progress').length,
      completed: currentTasks.filter(t => t.status === 'done').length,
      overdue: currentTasks.filter(t => t.due_date && new Date(t.due_date) < now && t.status !== 'done').length
    }
  }

  // 获取最近活动
  private async getRecentActivity(userId: string): Promise<TaskActivity[]> {
    // TODO: 从数据库获取用户最近活动
    return [
      {
        id: '1',
        taskId: '1',
        action: 'updated',
        timestamp: new Date('2024-01-12T10:30:00'),
        details: { field: 'status', oldValue: 'pending', newValue: 'in_progress' }
      }
    ]
  }

  // 获取用户偏好设置
  private async getUserPreferences(userId: string): Promise<UserPreferences> {
    // TODO: 从数据库获取用户偏好设置
    return {
      defaultPriority: 'medium',
      defaultCategory: '工作',
      reminderSettings: {
        enabled: true,
        advanceTime: 30
      },
      workingHours: {
        start: '09:00',
        end: '18:00'
      }
    }
  }

  // 构建AI上下文
  async buildAIContext(userId: string, sessionId?: string): Promise<AIContext> {
    const contextData = await this.getTaskContext(userId)
    
    return {
      userId,
      currentTasks: contextData.currentTasks,
      userPreferences: contextData.userPreferences,
      sessionId
    }
  }

  // 格式化任务信息为AI可理解的文本
  formatTasksForAI(tasks: Task[]): string {
    if (tasks.length === 0) {
      return '用户当前没有任务。'
    }

    const taskList = tasks.map(task => {
      const dueDate = task.due_date ? ` (截止: ${new Date(task.due_date).toLocaleDateString()})` : ''
      const tags = task.tags && task.tags.length > 0 ? ` [${task.tags.join(', ')}]` : ''
      return `- ${task.title}${dueDate} [${task.priority}] [${task.status}]${tags}`
    }).join('\n')

    return `用户当前任务列表:\n${taskList}`
  }

  // 格式化统计信息为AI可理解的文本
  formatStatsForAI(stats: TaskContextData['taskStats']): string {
    return `任务统计: 总计${stats.total}个任务, 待办${stats.pending}个, 进行中${stats.inProgress}个, 已完成${stats.completed}个, 逾期${stats.overdue}个`
  }
}

export const taskContextProvider = new TaskContextProvider()
export default taskContextProvider
